import { get, omit } from 'lodash';

/**
 * 参考 Array.map 编写的简易循环示例
 * @param {array<any>} tree 需要被循环的树
 * @param {function} fn 回调函数
 * @param {object} opt opt.loopChild = 'children' 循环结 默认key为 children
 * @returns {array<any>}
 */
export const treeLoopMap = (tree, fn, opt = {}) => {
  const loop = (tree, fn, opt = {}, parent = {}) => {
    const { loopChild = 'children' } = opt;
    return [...(tree || [])].map((item) => {
      const children = get(item, loopChild);
      const nextItem = (fn ? fn({ ...item }, parent) : omit(item, [loopChild])) || {};
      if (children) {
        nextItem[loopChild] = loop(children, fn, opt, { ...omit(item, [loopChild]) });
      }
      return {
        ...nextItem,
      };
    });
  };
  return loop(tree, fn, opt, {});
};
